package com.wlyuan.open.scanner.repository.impl;

import com.wlyuan.open.scanner.assembler.ScannerTopExtensionAssembler;
import com.wlyuan.open.scanner.constant.Constants;
import com.wlyuan.open.scanner.dao.entity.ExtensionDO;
import com.wlyuan.open.scanner.dao.mapper.ExtensionMapper;
import com.wlyuan.open.scanner.domain.extension.Extension;
import com.wlyuan.open.scanner.domain.extension.ExtensionConvert;
import com.wlyuan.open.scanner.repository.CustomerRepository;
import com.wlyuan.open.scanner.repository.ExtensionRepository;
import com.wlyuan.open.scanner.repository.ExtensionTopWarehouseRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @author lijing
 * @description
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class TopExtensionRepositoryImpl implements ExtensionRepository {
    private final ExtensionMapper extensionMapper;
    private final BaseOrderRepository baseOrderRepository;
    private final ExtensionTopWarehouseRepository extensionTopWarehouseRepository;
    private final CustomerRepository customerRepository;

    @Override
    public void sync() {
        logger.info("TOP定制数据同步");
        int count = extensionMapper.count();
        logger.info("TOP定制老数据数据量，size：{}", count);
        var pages = (int) Math.ceil(count * 1.0 / Constants.PAGE_SIZE);
        for (int i = 1; i <= pages; i++) {
            logger.info("开始同步TOP定制：第{}页，共{}页", i, pages);
            var list = extensionMapper.getTopOrderId(i, Constants.PAGE_SIZE);
            list.forEach(id -> {
                try {
                    var data = extensionMapper.getById(id);
                    if (data.getTenantId() == null) {
                        logger.error("extension ： {}，{}", id, data.getExtensionOrdercid());
                        baseOrderRepository.sync(null);
                    } else {
                        process(data);
                        baseOrderRepository.sync(ScannerTopExtensionAssembler.assemble(ExtensionConvert.convertTop(data)));
                    }

                } catch (Exception e) {
                    logger.error("TOP定制同步异常：{}，{}", id, e);
                    e.printStackTrace();
                }
            });
        }
        logger.info("TOP定制同步完成......");
    }

    @Override
    public Extension getById(Long extensionId) {
        return Optional.ofNullable(extensionId).map(id -> {
            var data = extensionMapper.getById(id);
            if (data.getTenantId() == null) {
                logger.error("extension ： {}，{}", id, data.getExtensionOrdercid());
                return null;
            }
            process(data);
            return ExtensionConvert.convertTop(data);
        }).orElse(null);
    }

    @Override
    public List<Long> getByTime(String startTime, String endTime) {
        return extensionMapper.getByTime(startTime, endTime);
    }

    @Override
    public void process(ExtensionDO data) {
        Optional.ofNullable(data).ifPresent(d -> {
            var orderId = d.getExtensionOrdercid();
            //物品
            var orderGoodsList = baseOrderRepository.getOrderGoodsByOrderId(orderId, d.getTenantId());
            d.setGoodsList(orderGoodsList);

            if (StringUtils.isNotBlank(d.getExtensionThirdeight())) {
                Optional.ofNullable(extensionTopWarehouseRepository.getByCode(d.getExtensionThirdeight())).ifPresent(w -> {
                    d.setExtensionThirdnine(w.getTopWarehouseshortname());
                });
            }

            //客户
            Optional.ofNullable(customerRepository.getCustomerById(d.getCustomerId())).ifPresent(c -> {
                data.setCName(c.getName());
                data.setCustomerType(c.getType());
                data.setCustomerTenantId(c.getTenantId());
            });
        });
    }

}
